package cn.promonkey.core.security;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.promonkey.core.dto.UserDto;
import cn.promonkey.api.log.entity.Log;
import cn.promonkey.api.log.service.LogService;
import cn.promonkey.core.base.Constants;
import cn.promonkey.core.toolkit.CommonUtils;
import cn.promonkey.core.toolkit.JsonUtils;
import cn.promonkey.core.utils.RedisUtils;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import cn.promonkey.core.toolkit.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SecurityService {
	
	@Autowired 
	private RedisUtils redisUtilsValue;
	
	@Autowired
	private LogService logServiceValue;

    @Value("${sso.auth.check_token}")
    private String checkTokenValue;

    @Value("${sso.Authorization}")
    private String AuthorizationValue;

    @Value("${sso.baseUrl}")
    private String baseUrlValue;

    @Value("${develop-platform.appId}")
    private Long appIdValue;

    private static String checkToken;

    private static String Authorization;

    private static String baseUrl;

    private static Long appId;
    
    private static RedisUtils redisUtils;
    
    private static LogService logService;

    private static HttpServletRequest request;

    private final HttpServletRequest requestValue;

    public SecurityService(HttpServletRequest requestValue){
        this.requestValue = requestValue;
    }

    @PostConstruct
    public void init () {
        checkToken = checkTokenValue;
        Authorization = AuthorizationValue;
        baseUrl = baseUrlValue;
        appId = appIdValue;
        request = requestValue;
        redisUtils = redisUtilsValue;
        logService = logServiceValue;
    }

    //项目内校验
    public static UserDto getCurrentUserAndCheck(String requestURI,String json){
    	String accessToken = request.getHeader("Authorization");
    	if(null == accessToken) {
    		return null;
    	}
    	Object uid = redisUtils.hget(Constants.ACCESS_TOKEN_HASH, accessToken);
		//Object refreshToken = redisUtils.hget(Constants.REFRESH_TOKEN_HASH, loginUser.getRefresh_token());
		UserDto dto = new UserDto();
		if(uid!=null) {
			redisUtils.hset(Constants.ACCESS_TOKEN_HASH, accessToken, uid, 30*24*60*60);
			//redisUtils.hset(Constants.ACCESS_TOKEN_HASH, refreshToken, uid, 3*30*24*60*60);
			Object businessId = redisUtils.hget(Constants.BUSINESS_ID, ""+uid);
			
			dto.setUserId((int)uid+0l);
			dto.setBusinessId((int)businessId+0l);
    		Log log = new Log();
    		log.setBusinessId((Integer)businessId);
    		log.setUserId((Integer)uid);
    		log.setSendTime(new Date());
    		log.setJson(json);
    		log.setInterfaceKey(requestURI);
    		//log.setMenuId(null);
    		log.setSystemId(appId.intValue());
    		logService.save(log);
			
			
		}else {
			return null;			
		}
		return dto;
    }
    
    //项目外校验
    public static UserDto getCurrentUserAndCheck2(String requestURI,String jsonInput){
		Integer index = requestURI.indexOf("?");
        if(index > -1){
            requestURI = requestURI.substring(0, index);
        }
        UserDto userDto = new UserDto();

        String accessToken = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(accessToken) && !("null").equals(accessToken)) {
            // 校验用户
            Map<String, String> header = new HashMap<>();
            header.put("Content-Type", "application/json");
            header.put("Authorization", Authorization);
            //拼接多参数
            JSONObject json = new JSONObject();
            json.put("grant_type", "check_token");
            json.put("access_token", accessToken);
            json.put("app_type", "dev");
            json.put("systemId", appId);
            json.put("interfaceKey", requestURI);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            json.put("sendTime", sdf.format(new Date()));
            //消息体
            json.put("json", jsonInput);

            log.info("校验登录,请求地址:{},请求头:{},请求参数:{}", checkToken, header, json);
            String s = HttpClientUtils.doPostRequest(baseUrl + checkToken, header, json, null);
            if(StringUtils.isNotBlank(s)){
                HashMap<Object, Object> result = JsonUtils.jsonToMap(s);
                System.out.println("oauth2校验请求获取的返回值：" + result);
                if (CommonUtils.isNotEmpty(result)) {
                    Object userData = result.get("data");
                    if(null != userData) {
                        ObjectMapper objectMapper = new ObjectMapper();
                        userDto = objectMapper.convertValue(userData, UserDto.class);
                    }
                    if(userDto.getUserId()==null) {
                    	//刷新token
                    	
                    	
                    }
                    return userDto;
                }
            }
            return null;
        }

        return userDto;
    }

}
